<?php

namespace app\company\controller\task\publish;

use app\BaseController;
use app\model\AreasModel;
use app\model\platform\PlatformTaskContinuousEvaluationModel;
use app\model\platform\PlatformTaskModel;
use app\model\platform\PlatformTaskRatingScaleModel;
use app\model\platform\PlatformTaskUnitModel;
use app\model\RatingScaleModel;
use app\model\UnitModel;
use think\App;

class Index extends BaseController
{
    protected $mode;

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->mode = new PlatformTaskModel();
    }

    /**
     * 发布任务
     * @return bool|string
     */
    public function PublishTask(): bool|string
    {
        $this->mode->startTrans();
        try {
            $taskData = $this->request->param('task');
            $rating_scale = $this->request->param('rating_scale');
            $unit_id = $this->request->param('uids');
            $this->validate($taskData, [
                'name|任务名称' =>  'require',
                'start_time|开始时间' =>  'require',
                'end_time|结束时间' =>  'require',
            ]);
            if (empty($unit_id) || empty($rating_scale)) throw new \Exception('请选择量表和单位！');
            $rating_scale_column = array_column($rating_scale, 'id');
            if (count($rating_scale_column) !== count(array_unique($rating_scale_column))) throw new \Exception('量表不能重复选择！');
            $taskData['rating_scale_count'] = count($rating_scale);
            $taskData['unit_count'] = count($unit_id);
            $taskData['company_id'] = $this->userData['company_id'];
            $taskData['areas_id'] = $this->userData['areas_id'];
            $taskData['uid'] = $this->userData['id'];
            $taskData['time'] = $time = time();
            if ($taskData['start_time'] >= $time && $taskData['end_time'] <= $time) {
                //在任务时间内将任务设为进行中
                $taskData['status'] = 2;
            }
            if (!empty($taskData['result_read_auth'])) {
                $taskData['result_read_auth'] = implode(',', $taskData['result_read_auth']);
            }
            $PlatformTaskRatingScaleModel = new PlatformTaskRatingScaleModel();
            $PlatformTaskUnitModel = new PlatformTaskUnitModel();
            $PlatformContinuousEvaluationModel = new PlatformTaskContinuousEvaluationModel();
            $task_id = $this->mode->insertGetId($taskData);
            //添加任务量表
            $task_rating_scale = [];
            $continuousData = [];
            foreach ($rating_scale as $item) {
                //预警连续测评
                $factor = $item['factor'] ?? [];
                $factor_id_column = array_column($factor, 'factor_id');
                if (count($factor_id_column) !== count(array_unique($factor_id_column))) throw new \Exception('连评因子不能重复选择！');
                foreach ($factor as $value) {
                    if ($item['id'] == $value['rating_scale_id']) throw new \Exception('预警连评量表不能和测评量表一样');
                    $continuousData[] = [
                        'task_id' => $task_id,
                        'rating_scale_id' => $item['id'],
                        'factor_id' => $value['factor_id'],
                        'continuity_rating_scale_id' => $value['rating_scale_id'],
                        'time' => $time
                    ];
                }
                //任务量表
                $task_rating_scale[] = [
                    'task_id' => $task_id,
                    'rating_scale_id' => $item['id'],
                    'time' => $time
                ];
            }
            //任务单位
            $task_unit = [];
            foreach ($unit_id as $v) {
                $task_unit[] = [
                    'task_id' => $task_id,
                    'unit_id' => $v,
                    'time' => $time
                ];
            }
            if (count($continuousData)) {
                $PlatformContinuousEvaluationModel->insertAll($continuousData);
            }
            if (count($task_rating_scale)) {
                $PlatformTaskRatingScaleModel->insertAll($task_rating_scale);
            }
            if (count($task_unit)) {
                $PlatformTaskUnitModel->insertAll($task_unit);
            }
            $this->mode->commit();
            return success([
                'task_id' => $task_id,
                'task_name' => $taskData['name'],
                'time' => $time,
                'start_time' => $taskData['start_time'],
                'end_time' => $taskData['end_time'],
                'status' => $taskData['status']??1,
                'unit_count' => $taskData['unit_count'],
                'user_name' => $this->userData['name'],
                'user_level' => $this->userData['level'],
            ], '添加成功！');
        } catch (\Exception $e) {
            $this->mode->rollback();
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 量表选择器
     * @return bool|string
     */
    public function RatingScaleSelector(): bool|string
    {
        try {
            $RatingScaleModel = new RatingScaleModel();
            $data = $RatingScaleModel->field('id,name')->where([
                ['company_id','=',$this->userData['company_id']],
//                ['areas_id','=',$this->userData['areas_id']],
                ['channel','=',3]
            ])->select()->toArray();
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 单位选择器
     * @return bool|string
     */
    public function UnitSelector(): bool|string
    {
        return (new \app\common\controller\Areas($this->app))->getLevelTree();
    }

    /**
     * 单位联动器
     * @return bool|string
     */
    public function UnitLinkage(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|ID' => 'require',
            ]);
            $where = [];
            $where[] = ['company_id','=',$this->userData['company_id']];
            $where[] = ['areas_id','=',$param['id']];
            $UnitModel = new UnitModel();
            $data = $UnitModel->field('id,name')->where($where)->select()->toArray();
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 单位id获取单位列表
     * @return bool|string
     */
    public function IdGetUnit(): bool|string
    {
        try {
            $id = $this->request->param('id');
            if (!is_array($id)) throw new \Exception('参数错误！');
            $UnitModel = new UnitModel();
            $data = $UnitModel->field('id,name')->where('id','in',$id)->withCount(['user'])->select()->toArray();
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }
}